package com.spider.im.chat.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.spider.im.chat.entity.ChatGroup;
import com.spider.im.chat.entity.ChatGroupUser;
import com.spider.im.chat.mapper.ChatGroupMapper;
import com.spider.im.chat.req.ChatGroupReq;
import com.spider.im.chat.service.ChatGroupService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 聊天群组表 服务实现类
 * </p>
 *
 * @author joy
 * @since 2025-04-23
 */
@Service
public class ChatGroupServiceImpl extends ServiceImpl<ChatGroupMapper, ChatGroup> implements ChatGroupService {

    @Resource
    private ChatGroupMapper chatGroupMapper;
    @Resource
    private ChatGroupUserService chatGroupUserService;

    @Transactional
    @Override
    public Long saveGroup(ChatGroupReq chatGroupReq) {
        ChatGroup chatGroup = new ChatGroup();
        BeanUtil.copyProperties(chatGroupReq, chatGroup);
        chatGroupMapper.insert(chatGroup);
        List<Long> groupUsers = new ArrayList<>(chatGroupReq.getGroupUsers());
        groupUsers.add(chatGroupReq.getGroupOwner());
        if (CollectionUtil.isNotEmpty(groupUsers)) {
            chatGroupUserService.saveBatch(groupUsers.stream().map(userId -> {
                return ChatGroupUser.builder().groupId(chatGroup.getId()).userId(userId).build();
            }).toList());
        }
        return chatGroup.getId();
    }
}
